<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class TokenController extends BaseController
{

    public function __construct(Request $request)
    {
        parent::__construct($request);

        $this->middleware(function ($request, $next) { //控制器中间件

            $acturl = $request->decodedPath();
            if ($acturl == 'api/commontoken/testform') {
                $formtoken = $request->header('formtoken');
                $mid = $this->mangerinfo['id'];
                $lock_str_title = 'form_' . $mid;


                if (!checkApiCacheToken($lock_str_title, $formtoken)) {
                    return response()->json(['code' => '001', 'msg' => '无效token非法访问']);
                }


                $lock = lockApiCacheToken($lock_str_title, 20);

                if (!$lock->get()) {
                    return response()->json(['code' => '001', 'msg' => '连续点击了']);
                }

                $response = $next($request);

                lockReleaseApiCacheToken($lock);
                delApiCacheToken($lock_str_title);
            } else {
                $response = $next($request);
            }
            return $response;
        });
    }
    public function createtoken(Request $request)
    {
        $mid = $this->mangerinfo['id'];
        $lock_str_title = 'form_' . $mid;
        $formtoken = apiCacheToken($lock_str_title);

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['formtoken' => $formtoken]]);
    }

    public function testform(Request $request)
    {

        //逻辑开始
        sleep(20);
        //逻辑结束

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
